package ssen.mvc.base {
import flash.events.Event;
import flash.events.IEventDispatcher;
import flash.utils.Dictionary;

import ssen.mvc.core.ICommand;
import ssen.mvc.core.ICommandMap;
import ssen.mvc.core.IInjector;

public class CommandMap implements ICommandMap {
	private var injector:IInjector;
	private var dic:Dictionary;
	private var dispatcher:IEventDispatcher;

	public function CommandMap(injector:IInjector) {
		this.injector=injector;
		dispatcher=injector.getInstance(IEventDispatcher);
		dic=new Dictionary;
	}

	public function map(type:String, commandClass:Class):void {
		if (dic[commandClass] !== undefined) {
			throw new Error("mapped command class!!!");
		}

		dic[type]=commandClass;
		dispatcher.addEventListener(type, listener);
	}

	public function unmap(type:String):void {
		if (dic[type] === undefined) {
			throw new Error("undefined this event type!!! " + type);
		}

		delete dic[type];
		dispatcher.removeEventListener(type, listener);
	}

	public function dispose():void {
		for (var type:String in dic) {
			dispatcher.removeEventListener(type, listener);
		}
		dic=null;
	}

	private function listener(event:Event):void {
		if (dic[event.type] !== undefined) {
			var commandClass:Class=dic[event.type];
			var command:ICommand=new commandClass();
			command.execute(event);
		}
	}
}
}
